<template>
  <el-dialog v-model="dialogVisible" title="新增目录">
    <el-form :model="dialogProps.rowData" ref="formRef" :rules="rules">
      <el-form-item label="目录名称" prop="name">
        <el-input v-model="dialogProps.rowData.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { ref } from "vue";

const dialogVisible = ref(false);

interface DialogProps {
  rowData: any;
  api?: (params: any) => Promise<any>;
  refresh?: (params: any) => Promise<any>;
}

const initData: any = {
  name: ""
};

const dialogProps = ref<DialogProps>({
  rowData: JSON.parse(JSON.stringify(initData))
});

const acceptParams = (params: any) => {
  dialogProps.value = params;
  if (!params.rowData) {
    dialogProps.value.rowData = JSON.parse(JSON.stringify(initData));
  }
  dialogVisible.value = true;
};

const rules: FormRules = {
  name: [
    { required: true, message: "名称不可为空" },
    { max: 6, min: 1, message: "字符在1-6之间" }
  ]
};

// -----------表单
const formRef = ref<FormInstance>();

const submit = () => {
  formRef.value?.validate(async valid => {
    if (valid) {
      try {
        await dialogProps.value.api!(dialogProps.value.rowData);
        ElMessage.success("成功!");
        await dialogProps.value.refresh!({});
        dialogVisible.value = false;
      } catch (error) {}
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style></style>
